Skip to content

fix: make HashUtil::HashBytes more platform independent #814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 13, 2025

Conversation

polyominal
Copy link
Contributor

https://github.com/polyominal/bustub/blob/9988c8503cc3e5107cc750c651ebeaef2efe8ce6/src/include/common/util/hash_util.h#L32-L39

The hash function uses raw bytes[i] in char. This creates a subtle bug. C++ doesn't define whether char is signed or unsigned.

For byte values over 127, this matters:

  • Signed platforms: values become negative (the expected behavior)
  • Unsigned platforms: values stay positive (0-255)

This bit me during HyperLogLog project:
https://github.com/polyominal/bustub/blob/9988c8503cc3e5107cc750c651ebeaef2efe8ce6/test/primer/hyperloglog_test.cpp#L58-L108

My code failed on my machine (unsigned char) but passed elsewhere (signed char).

Proposed fix: Cast to int8_t for consistent behavior.

hash = ((hash << 5) ^ (hash >> 27)) ^ static_cast<int8_t>(bytes[i]);

This should enable more machines to work. Any downsides to consider?

Copy link
Member

@connortsui20 connortsui20 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, seems like a strictly better change. Thank you!

@connortsui20 connortsui20 merged commit 53b85bb into cmu-db:master May 13, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants